/*
 * HistogramFeature.cpp
 *
 *  Created on: Feb 23, 2011
 *      Author: johang
 */


#include "HistogramFeature.h"

HistogramFeature::HistogramFeature(Feature * feat,int* binsi ,float* mini , float* maxi, TF ** transf) {
	last_x = -1; last_y = -1;
	printf("hist feature created\n");
	transformationfunction = transf;
	int input_dim = feat->dims;
	bins =  binsi;
	min = mini;
	max = maxi;
	accum = new int[input_dim];
	int total_bins = 1;
	printf("----Setup----\n");
	for(int i = input_dim-1;i>=0;i--)
	{
		accum[i]=total_bins;
		total_bins*=bins[i];
		printf("Before: %f %f ",mini[i],maxi[i]);
		mini[i]=transformationfunction[i]->evaluate(mini[i]);
		maxi[i]=transformationfunction[i]->evaluate(maxi[i]);
		printf(" || After: %f %f \n",mini[i],maxi[i]);
	}
	dims = total_bins;
	feature = feat;
}

HistogramFeature::~HistogramFeature() {
	// TODO Auto-generated destructor stub
}

void HistogramFeature::getResponse(float * output,Point *** points, int x, int y ,int * divi){
	last_x = x; last_y = y;
	int total_bins =dims;
	int input_dim = feature->dims;
	float * tmp = new float[total_bins];
	int * tmp_arr = new int[input_dim];
	for(int i = 0; i < total_bins;i++)
	{
		tmp[i] = 0;
	}
	float nr_for_normalize = 0;
	while(feature->canGetResponse(points,x,y))
	{
		feature->getResponse(tmp,points,x,y,divi);
		for(int q = 0; q < feature->dims;q++){
			tmp_arr[q] = (transformationfunction[q]->evaluate(tmp[q])-min[q])*((float)(bins[q]))/(max[q]-min[q]);
			if(tmp_arr[q]<0)
			{
				tmp_arr[q] = 0;
			}
			else if(tmp_arr[q]>=bins[q])
			{
				tmp_arr[q]= bins[q]-1;
			}
		}
		int index = getIndex(tmp_arr);
		output[index]+=1;
		nr_for_normalize++;
	}
	
	//printf("\n");
	for(int i = 0; i < total_bins;i++)
	{
		//printf("%i ",(int)output[i]);
		if(nr_for_normalize>100){	output[i]/=nr_for_normalize;}
		else{				output[i]=0;}
	}
	/*printf("----------------\n");
	for(int i = 0; i < total_bins;i++)
	{
		printf("%i ",(int)output[i]);
	}
	printf("\n");*/
	
	
}

int HistogramFeature::getIndex(int * pos){
	int ret = 0;
	int input_dim = feature -> dims;
	for(int i = 0;i<input_dim;i++)
	{
	//printf("i=%i -> %i += %i*%i\n",i,ret,accum[i],pos[i]);
	ret += accum[i]*pos[i];
	}
	return ret;
}
